<?php
if (function_exists('session_start')) session_start();

class Mysql {
  /** @var resource to hold Mysql server connection */
  private $_resource;
  /** @var string to hold the current SQL statement */
  private $_sql;
  
  public function __construct() {
    
    $this->_resource = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die('Could not connect: '.mysql_error());
    mysql_query('SET NAMES UTF8',$this->_resource);

    if(!$this->_resource) {
      echo 'Could not connect: '.mysql_error();
      exit();
    }
    mysql_select_db(DB_NAME,$this->_resource) or die ('Could not select database');
  }

  public function query($sql) {
    $this->_sql = $sql;

    $result = mysql_query($this->_sql,$this->_resource);
    
    if(!$result) {
      echo mysql_errno().':'.mysql_error().'<pre>'.$this->_sql.'</pre>';
      exit();
    }
    else return $result;
  }
  
  /**
  * @return Ojbect from a given resource result
  */
  public function get_object($result) {
    return mysql_fetch_object($result);
  }
  
  /**
  * @return Associative array from a given resource result
  */
  public function get_assoc($result) {
    return mysql_fetch_assoc($result);
  }
  
  /**
  * @return Number of affected rows in a given resource result
  */
  public function num_rows($result) {
    return mysql_num_rows($result);
  }
  
  /**
  * @return Last inserted ID from insert statement
  */
  public function last_id() {
    return mysql_insert_id();
  }
  
  /**
  * Locks and blocks given table
  */
  public function lock($table) {
    $this->query('LOCK TABLES '.$table.' WRITE');
  }
  
  /**
  * Unlocks all tables and release any locks 
  */
  public function unlock() {
    $this->query('UNLOCK TABLES');
  }
}

$db = new Mysql();

function query($sql) {
  global $db;
  return $db->query($sql);
}

?>